<?php
namespace Home\Controller;

class ReplyController extends BaseController
{
    public function index()
    {
        $userInfo = $this->checkLogin();

        $pid = I('get.pid'); // 获取帖子ID
        //var_dump( $pid);
        // 每次访问时，帖子阅读数自增
        $model = M('Post');
        $model->where(['id' => $pid])->setInc('view_num');
        //var_dump($model);
        //var_dump($pid);
        $postContent = M('post')
        ->field('bbs_post.*, bbs_member.name,bbs_member.uface')
        ->join('bbs_member ON bbs_post.uid = bbs_member.id')
        ->where(['bbs_post.id' => $pid])
        ->find(); // 读取主贴信息
       
        $replys = M('Reply')
        ->field('bbs_reply.*, bbs_member.name, bbs_member.uface, bbs_member.auth')
        ->join('bbs_member ON bbs_reply.uid=bbs_member.id')
        ->where(['pid' => $pid])
        ->select();
        //var_dump($replys);
        $this->assign('post', $postContent);
        $this->assign('replys', $replys);
        $this->display();

        // $sql = "SELECT bbs_post.*,bbs_member.name,bbs_member.id FROM `bbs_post` INNER JOIN bbs_member ON bbs_post.uid = bbs_member.id WHERE bbs_post.id = '1' LIMIT 1";
        // $list = query($sql);
    }

    // 接收回帖内容
    public function add()
    {
        $userInfo = $this->checkLogin();

        if($this->hasSensitiveWord(I('post.content'))) $this->error('回复中含有敏感词，请重新编辑!');

        $reply = I('post.');
        $reply['uid'] = $userInfo['id'];
        
        $model = D('reply');
        $res = $model->create($reply);
        if($res === false) {
            $this->error($model->getError());
        } else {
            $id = $model->add();
            if($id) {
                M('Post')->where(['id'=>$reply['pid']])->setInc('reply_num');
                M('Post')->where(['id'=>$reply['pid']])->setField('update_time', time());
                $this->redirect('Reply/index', ['pid' => $reply['pid']]);
            } else {
                $this->error('回复失败');
            }
        }
    }
     /**
     * 检测字符串中是否含有敏感词
     * @param string $str - 要检测的字符串
     * @return bool true: 含有敏感词 false: 没有敏感词
     */
    private function hasSensitiveWord($str)
    {
        $sensitiveWordList = ['草', '法克', '嘤嘤嘤','你妈的','草拟吗'];

        foreach($sensitiveWordList as $word) {
            $pos = strpos($str, $word);
            if($pos !== false) {
                return true;
            }
        }

        return false;
    }
}